package com.xiaobai.netease_news.fragments;


import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xiaobai.netease_news.R;
import com.xiaobai.netease_news.adapters.HeaderPagerAdapter;
import com.xiaobai.netease_news.adapters.NewsListAdapter;
import com.xiaobai.netease_news.constants.Constant;
import com.xiaobai.netease_news.model.HeadAD;
import com.xiaobai.netease_news.model.Header;
import com.xiaobai.netease_news.model.ResponseData;
import com.xiaobai.netease_news.utils.CommonHttpUtil;
import com.xiaobai.netease_news.utils.ImageUniversalLoaderConfiguration;
import com.xiaobai.netease_news.views.CircleProgressBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class NewsListFragment extends Fragment
        implements SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener,
        ViewPager.OnPageChangeListener, AdapterView.OnItemClickListener {

    private List<ResponseData> responseDatas;

    private static final String ARG_POSITION = "position";

    private String s = "headline";

    private String currentSelectedTitle;
    private NewsListAdapter adapter;
    private int i = 1;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean isBottom;
    private LinearLayout newsLoading;
    private CircleProgressBar newsLoadingProgressBar;
    private boolean isProgressBarShow;

    private LinearLayout headerView;
    private String[] headerPicUrls = new String[4];
    private String[] headerTitles = new String[4];
    private HeaderPagerAdapter headerPagerAdapter;
    private DisplayImageOptions options = ImageUniversalLoaderConfiguration.initOptions();
    private List<ImageView> imgList;
    private TextView headerTitle;
    private ViewPager mViewPager;

    public NewsListFragment() {
    }

    public static NewsListFragment newInstance(int position) {
        NewsListFragment newsListFragment = new NewsListFragment();
        Bundle b = new Bundle();
        b.putInt(ARG_POSITION, position);
        newsListFragment.setArguments(b);
        return newsListFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        responseDatas = new ArrayList<>();
        adapter = new NewsListAdapter(getActivity(), responseDatas);

        Bundle args = getArguments();
        if (args != null) {
            currentSelectedTitle = args.getString(Constant.ARG_CONTENT_LIST_TYPE);
            Log.d("current", currentSelectedTitle);
        }

        if (currentSelectedTitle.equals(Constant.NEWS_TOPIC))
            s = "headline";
        else
            s = "list";

        new HeaderTask().execute("http://c.3g.163.com/nc/ad/headline/android/0-3.html");
        new NewsListTask().execute(s, currentSelectedTitle, "0");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_news_list, container, false);

        newsLoading = (LinearLayout) view.findViewById(R.id.news_list_loading_layout);

        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.news_swipe_refresh);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(this);

        headerView = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.news_header_layout, null);
        mViewPager = (ViewPager) headerView.findViewById(R.id.header_news_img);
        headerTitle = (TextView) headerView.findViewById(R.id.header_news_title);
        initPics();
        headerPagerAdapter = new HeaderPagerAdapter(getActivity(), imgList, mViewPager);
        mViewPager.setAdapter(headerPagerAdapter);

        // 刚开始显示时, 把当前的页面切换到MAX_VALUE/2的位置上.
        int currentItem = Integer.MAX_VALUE / 2;
        // 把currentItem减去余数, 可以切换到第一张图片
        currentItem = currentItem - ((Integer.MAX_VALUE / 2) % imgList.size());
        headerTitle.setText(headerTitles[0]);
        mViewPager.setCurrentItem(currentItem); // 设置当前选中的页面  //调用 onPageSelected

        mViewPager.setOnPageChangeListener(this);

        ListView listView = (ListView) swipeRefreshLayout.findViewById(R.id.item_list);
        listView.addHeaderView(headerView);

        listView.setOnScrollListener(this);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);

        newsLoadingProgressBar = (CircleProgressBar) view.findViewById(R.id.news_loading);
        if (!isProgressBarShow)
            newsLoadingProgressBar.setVisibility(View.VISIBLE);
        else
            newsLoadingProgressBar.setVisibility(View.GONE);

        isProgressBarShow = true;

        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString(ARG_POSITION, currentSelectedTitle);
    }

    @Override
    public void onViewStateRestored(Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
    }

    @Override
    public void onRefresh() {
        if (currentSelectedTitle.equals(Constant.NEWS_TOPIC))
            s = "headline";
        else
            s = "list";

        new HeaderTask().execute("http://c.3g.163.com/nc/ad/headline/android/0-3.html");
        new NewsListTask().execute(s, currentSelectedTitle, "0");
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (isBottom && scrollState == SCROLL_STATE_IDLE) {
            newsLoading.setVisibility(View.VISIBLE);
            if (currentSelectedTitle.equals(Constant.NEWS_TOPIC))
                s = "headline";
            else
                s = "list";

            new NewsListTask().execute(s, currentSelectedTitle, "0" + (i * 20));
            i++;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        isBottom = (firstVisibleItem + visibleItemCount) == totalItemCount;
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int newPos = position % imgList.size();
        headerTitle.setText(headerTitles[newPos]);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // TODO 转跳到对应的新闻详情页面
        Object item = parent.getAdapter().getItem(position);
        ResponseData responseData = (ResponseData) item;
        String url_3w = responseData.getUrl_3w();
        String tags = responseData.getTags();
        if (url_3w != null) {
            Log.d("url_3w", tags);
            Log.d("url_3w", url_3w);
        }
    }

    private class NewsListTask extends AsyncTask<String, Void, JSONObject> {
        private String _id = null;
        private String num = null;

        @Override
        protected JSONObject doInBackground(String... params) {
            _id = params[1];
            num = params[2];
            String url = "http://c.3g.163.com/nc/article/" + params[0] + "/" + params[1] + "/" + params[2] + "-20.html";

            byte[] bytes = CommonHttpUtil.doGet(url);
            if (bytes != null) {
                try {
                    String jsonString = new String(bytes, "utf-8");
                    return new JSONObject(jsonString);
                } catch (UnsupportedEncodingException | JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            if (newsLoadingProgressBar.getVisibility() == View.VISIBLE)
                newsLoadingProgressBar.setVisibility(View.GONE);

            swipeRefreshLayout.setRefreshing(false);
            newsLoading.setVisibility(View.GONE);

            if (jsonObject != null) {

                List<ResponseData> datas = new ArrayList<>();

                try {
                    JSONArray jsonArray = jsonObject.getJSONArray(_id);

                    JSONObject o = jsonArray.getJSONObject(0);
                    Header h = new Header();
                    h.parseJson(o);
                    String imgsrc = h.getImgsrc();
                    String title = h.getTitle();

//                    Log.d("imgsrc", imgsrc);

                    headerPicUrls[0] = imgsrc;
                    headerTitles[0] = title;

                    for (int i = 1; i < jsonArray.length(); i++) {
                        JSONObject object = jsonArray.getJSONObject(i);
                        ResponseData responseData = new ResponseData();
                        responseData.parseJson(object);

                        datas.add(responseData);
                    }

                    if (num.equals("0")) {
                        responseDatas.clear();
                        responseDatas.addAll(0, datas);
                    } else
                        responseDatas.addAll(datas);

                    adapter.notifyDataSetChanged();
//                    headerPagerAdapter.notifyDataSetChanged();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    }

    private class HeaderTask extends AsyncTask<String, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(String... params) {

            String url = params[0];

            byte[] bytes = CommonHttpUtil.doGet(url);
            if (bytes != null) {
                try {
                    String jsonString = new String(bytes, "utf-8");
                    return new JSONObject(jsonString);
                } catch (UnsupportedEncodingException | JSONException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }

        @Override
        protected void onPostExecute(JSONObject jsonObject) {
            try {
                if (jsonObject != null) {
                    JSONArray array = jsonObject.getJSONArray("headline_ad");
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject o = array.getJSONObject(i);
                        HeadAD had = new HeadAD();
                        had.parseJson(o);

                        String imgsrc = had.getImgsrc();
                        String title = had.getTitle();

                        headerPicUrls[i + 1] = imgsrc;
                        headerTitles[i + 1] = title;
                    }
                }
//                adapter.notifyDataSetChanged();
//                headerPagerAdapter.notifyDataSetChanged();

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    public void initPics() {
        imgList = new ArrayList<>();
        ImageView iv;
        for (int i = 0; i < headerPicUrls.length; i++) {
//            Log.d("picurl", headerPicUrls[i]);
            iv = new ImageView(getActivity());
            ImageLoader.getInstance().displayImage(headerPicUrls[i], iv, options);
            imgList.add(iv);
        }
    }

}
